<?php
error_reporting(E_ALL ^E_NOTICE);
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

$_MAMBOTS->registerFunction( 'onPayProsessStart', 'jeProcessAuthorizeStart' );
$_MAMBOTS->registerFunction( 'onPayProsessFinish', 'jeProcessAuthorizeFinish' );
//print_r($_POST);
//print_r($_GET);
//exit;
function jeProcessAuthorizeFinish()
{
    $processor = mosGetParam( $_REQUEST, 'processor'); // success or fail
    
    if($processor != '.authorize') return false;
    
    
    $success = mosGetParam( $_REQUEST, 'x_response_code');
    $order['id'] = mosGetParam( $_REQUEST, 'x_invoice_num');
    $order['pay'] = ($success == 1 ? 'success' : 'fail');
    $order['gateway'] = $processor;
    $order['gateway_id'] = mosGetParam( $_REQUEST, 'x_trans_id');
    
	if($success != 1) return;
	
    return $order;
}

function jeProcessAuthorizeStart( $params )
{
    Global $my, $mosConfig_live_site;
    if($params['processor'] != '.authorize') return;
    global $database;

    $query = "SELECT id"
    . "\n FROM #__mambots"
    . "\n WHERE element = 'joomlaequipment.payprocessor{$params[processor]}'"
    . "\n AND folder = 'system'"
    ;
    $database->setQuery( $query );
    $id     = $database->loadResult();
    $mambot = new mosMambot( $database );
    $mambot->load( $id );
    $botParams = new mosParameters( $mambot->params );
  
    $mid 	= $botParams->def( 'mid');
    $cc 	= $botParams->def( 'cc');
    $tran_key	= $botParams->def( 'tran_key');
    
    if(!$mid || !$params['order_amount'] || !$tran_key )
    {
        echo "Error Payment Processing: some of the params passed are empty<br>$vendor  - $mid - $params[order_amount] -  $tran_key";
        return;
    }
    $param['option'] = mosGetParam( $_REQUEST, 'option');
    $param['task']   = 'pay';
    $param['processor'] = $params['processor'];
    $param['x_invoice_num'] = $params['order_id'];
    $rurl = jpArray2Url($param);
    // layout fields
    //if($botParams->def( 'logo')) $param['x_logo_url'] = $botParams->def( 'logo');
    if($botParams->def( 'bgi'))  $param['x_background_url'] = $botParams->def( 'bgi');
    if($botParams->def( 'bg'))   $param['x_color_background'] = $botParams->def( 'bg');
    if($botParams->def( 'lc'))   $param['x_color_link'] = $botParams->def( 'lc');
    if($botParams->def( 'tc'))   $param['x_color_text'] = $botParams->def( 'tc');
    
    if($botParams->def( 'prepend')) $param['x_header_html_payment_form'] = $botParams->def( 'prepend');
    if($botParams->def( 'apend'))   $param['x_footer_html_payment_form'] = $botParams->def( 'apend');
    
    if($botParams->def( 'demo') == 'TRUE') $param['x_test_request'] = 'TRUE';
    
    if($botParams->def( 'mailc') == 'TRUE')   $param['x_email_customer'] = 'TRUE';
    if($botParams->def( 'copy'))   $param['x_merchant_email'] = $botParams->def( 'copy');
    
    $param['x_login'] = $mid;
    $param['x_amount'] = $params['order_amount'];//number_format(, 2, '.');
    $param['x_invoice_num'] = $params['order_id'];
    $param['x_description'] = $params['order_title'];
    $param['x_show_form']   = 'PAYMENT_FORM';
    
    // Customer information
    $param['x_first_name'] = $my->name;
    $param['x_cust_id'] = $my->id;
    $param['x_email'] = $my->email;
    $param[session_name()] = session_id();
    
        
    // Custom Fields
    
    if($botParams->def('relay'))
    {
        $param['x_relay_response'] = 'TRUE';
        $param['x_relay_url'] = urlencode($mosConfig_live_site.'/index.php?'.$rurl);
    }
    
    
    srand(time());
    $param = jpInsertFP ($param, $mid, $tran_key, $params['order_amount'], rand(1, 1000));//, $cc);
    //print_r($param);
    //exit; 
    $url = 'https://secure.authorize.net/gateway/transact.dll?'.jpArray2Url($param);
    //$url = 'https://test.authorize.net/gateway/transact.dll?'.jpArray2Url($param);
    //echo $url;
    //exit;
    //var_dump( $botParams->get('relay'));
    //echo str_replace("&", "<BR>", $url);
    header("location: $url");
}

if(!defined('JP_IMPLODE'))
{
    define('JP_IMPLODE', 1);
    function jpArray2Url($param)
    {
        foreach($param AS $k => $v)
        {
            $out[] = "$k=$v";
        }
        return implode('&', $out );
    }
}


// Calculate and return fingerprint
// Use when you need control on the HTML output
function jpCalculateFP ($loginid, $x_tran_key, $amount, $sequence, $tstamp, $currency = "")
{
    return (jpHmac ($x_tran_key, $loginid . "^" . $sequence . "^" . $tstamp . "^" . $amount . "^" . $currency));
}


// Inserts the hidden variables in the HTML FORM required for SIM
// Invokes hmac function to calculate fingerprint.

function jpInsertFP ($param, $loginid, $x_tran_key, $amount, $sequence, $currency = "")
{
    $tstamp = time ();
    
    $fingerprint = jpHmac ($x_tran_key, $loginid . "^" . $sequence . "^" . $tstamp . "^" . $amount . "^" . $currency);
    
    $param['x_fp_sequence'] = $sequence;
    $param['x_fp_timestamp'] = $tstamp;
    $param['x_fp_hash'] = $fingerprint;
    
    return $param;
}
if(extension_loaded('mhash'))
{
    function jpHmac ($key, $data)
    {
        return (bin2hex (mhash(MHASH_MD5, $data, $key)));
    }
}
else
{
    function jpHmac ($key, $data)
    {
       // RFC 2104 HMAC implementation for php.
       // Creates an md5 HMAC.
       // Eliminates the need to install mhash to compute a HMAC
       // Hacked by Lance Rushing
       $b = 64; // byte length for md5
       if (strlen($key) > $b) {
           $key = pack("H*",md5($key));
       }
       $key  = str_pad($key, $b, chr(0x00));
       $ipad = str_pad('', $b, chr(0x36));
       $opad = str_pad('', $b, chr(0x5c));
       $k_ipad = $key ^ $ipad ;
       $k_opad = $key ^ $opad;
       return md5($k_opad  . pack("H*",md5($k_ipad . $data)));
    }
}
?>